<template>
  <div class="ui-button flex mr-1" :class="{ hidden: conditionProperty.hidden || info.extension.hidden.value }">
    <el-button
      :ref="info._id"
      v-ui-ref="vSetRef"
      :circle="info.extension.circle.value"
      :disabled="conditionProperty.disabled || info.extension.disabled.value"
      :plain="info.extension.plain.value"
      :round="info.extension.round.value"
      :size="info.extension.size.value"
      :type="info.extension.type.value"
      @click="openTolead"
    >
      <vui-icon v-if="info.extension.icon.value" :icon="info.extension.icon.value" />
      <template v-if="!info.extension.circle.value">
        {{ info.extension.value.value }}
      </template>
    </el-button>
    <!-- 标签页配置弹框 -->
    <el-dialog
      v-if="toleadModal"
      v-model="toleadModal"
      :append-to-body="true"
      :title="translateTitle('Ve.elements.导入数据')"
      width="60%"
      @close="dialogClose"
    >
      <el-steps :active="active" align-center>
        <el-step :title="translateTitle('Ve.elements.上传模版数据')">
          <template #icon>
            <vui-icon v-if="active == 2" icon="check-line" style="color: #1d2c78" />
          </template>
        </el-step>
        <el-step :title="translateTitle('Ve.elements.模版数据检测')" />
      </el-steps>
      <div v-if="active == 1">
        <div class="hint_">
          <p class="hint-explain">
            <vui-icon icon="error-warning-fill" style="color: #ea8724" />
            {{ translateTitle('Ve.elements.请使用系统要求模版按格式要求填写数据') }}
          </p>
        </div>
        <div class="box_">
          <div class="left-box"></div>
          <div class="text-left right-width">
            <p class="text-color cursor-pointer" @click="download">
              <vui-icon icon="download-2-line " style="color: #3270ff" />
              {{ translateTitle('Ve.elements.下载模版填写导入数据信息') }}
            </p>
            <p class="text-tips">{{ translateTitle('Ve.elements.请按照数据模版的格式准备导入数据') }}</p>
          </div>
        </div>
        <div class="box_">
          <div class="left-box"></div>
          <vui-upload
            v-if="toleadModal"
            :ref="'fileUploadRef' + info._id"
            class="text-left right-width"
            :file-name="requestOption.name"
            :limit="1"
            :post-data="requestOption.postData"
            :url="requestOption.url"
            @uploadSuccess="uploadSuccess"
          >
            <div>
              <p class="text-color">
                <vui-icon icon="upload-2-line" style="color: #3270ff" />
                {{ translateTitle('Ve.elements.点击或将填好的信息表拖拽到这里上传') }}
              </p>
              <p class="text-tips">{{ translateTitle('Ve.elements.文件后缀名必须为xls或xlsx') }}</p>
            </div>
          </vui-upload>
        </div>
        <div class="box_">
          <div class="left-box"></div>
          <div class="text-left right-width">
            <div>
              <span>{{ translateTitle('Ve.elements.数据有重复时选择') }}:</span>
              <el-select v-model="value" :placeholder="translateTitle('Ve.elements.请选择')">
                <el-option v-for="item in sqlModelOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </div>
          </div>
        </div>
        <div class="footer_">
          <el-button type="primary" @click="clickUpload">{{ translateTitle('Ve.elements.下一步') }}</el-button>
        </div>
      </div>
      <div v-else>
        <div v-if="toleadSuccess" class="abnormal-hint">
          <p class="text-center">
            <vui-icon icon="checkbox-circle-fill" style="color: springgreen" />
            {{ translateTitle('Ve.elements.数据无异常') }}
          </p>
        </div>
        <div v-else>
          <div v-if="!info.extension.errorTable.value">
            <div class="abnormal-hint">
              <p class="text-center">
                <vui-icon icon="alert-fill" style="color: #ea8724; font-size: 60px" />
              </p>
              <p class="err-msg text-center"></p>
            </div>
          </div>
          <div v-else>
            <div>
              <vui-icon icon="alert-fill" style="color: #098ae8" />
              {{ translateTitle('Ve.elements.共导入') }}{{ gridOptions.data.length }}{{ translateTitle('Ve.elements.条数据导入成功')
              }}{{ gridOptions.data.filter((el) => el.IMPORT_STATUS === 'OK').length }}{{ translateTitle('Ve.elements.条')
              }}{{ translateTitle('Ve.elements.失败') }}{{ gridOptions.data.filter((el) => el.IMPORT_STATUS === 'ERROR').length
              }}{{ translateTitle('Ve.elements.条') }}
            </div>
            <vxe-grid v-bind="gridOptions">
              <template #status="{ row }">
                <div>
                  <span v-if="row.IMPORT_STATUS === 'ERROR'" class="status status-error"></span>
                  <span v-else class="status status-success"></span>
                  {{ row.IMPORT_STATUS === 'OK' ? translateTitle('Ve.elements.成功') : translateTitle('Ve.elements.失败') }}
                </div>
              </template>
            </vxe-grid>
          </div>
        </div>
        <div class="footer_">
          <el-button type="primary" @click="confirmDialog">{{ translateTitle('Ve.elements.确定') }}</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import { translateTitle } from '@/utils/i18n'
  import { defineComponent } from 'vue'
  import { UiMixin, RefsInjectMixin, ConditionMixin } from '@ve/mixin'
  import request from '@/utils/request'
  import { GFCD } from '@/utils/utils'
  export default defineComponent({
    name: 'UiTolead',
    components: {},
    mixins: [UiMixin, RefsInjectMixin, ConditionMixin],
    data() {
      return {
        toleadModal: false,
        active: 1,
        templateForm: {
          '#EXPORT_WHERE#': {
            TEMPLATE_ID: '',
            FIELD_ID: '',
          },
          '#EXPORT_SQL_ID#': '',
          '#EXPORT_API_NAME#': '',
          '#QUERY_SORT#': {
            SHOW_SEQUENCE: 'ASC',
          },
          '#EXPORT_FILE_NAME#': '',
          '#EXPORT_FILE_TYPE#': 'xlsx',
          '#EXPORT_SHEET_NAME#': '',
        },
        toleadSuccess: true,
        options: {},
        sqlModelOptions: [
          { value: 'DELETE_INSERT', label: this.translateTitle('Ve.elements.数据重复时删除插入') },
          { value: 'UPDATE', label: this.translateTitle('Ve.elements.数据重复时更新数据') },
          { value: 'REJECT', label: this.translateTitle('Ve.elements.数据重复时报错提示') },
          { value: 'NEXT', label: this.translateTitle('Ve.elements.数据重复时忽略跳过') },
        ],
        value: 'REJECT',
        gridOptions: {
          height: 300,
          size: 'mini',
          columnConfig: {
            resizable: true,
          },
          columns: [
            { field: 'SERIAL_NUMBER', width: 100, title: this.translateTitle('Ve.elements.序号'), align: 'center', sortable: true },
            {
              field: 'IMPORT_STATUS',
              title: this.translateTitle('Ve.elements.状态'),
              align: 'center',
              sortable: true,
              width: 100,
              slots: {
                default: 'status',
              },
            },
            { field: 'IMPORT_MSG', title: this.translateTitle('Ve.elements.导入描述'), align: 'center', sortable: true },
          ],
          data: [],
        },
      }
    },
    computed: {
      requestOption() {
        return {
          postData: {
            method: this.info.extension.toleadMethod.value,
            data: this.requestData(),
          },
          name: 'uploadFile',
          url: this.info.extension.toleadUrl.value,
        }
      },
    },
    methods: {
      translateTitle,
      //上传取模板配置的自定义参数，多个模板就多个对象(暂不考虑绑定表格数据)；模板配置增加自定义参数
      requestData() {
        let data = []
        let obj = {}
        let request = []
        if (this.info.extension.requestData && this.info.extension.requestData.value) {
          this.info.extension.requestData.value.forEach((row) => {
            obj[row.key] = row.value
          })
        }
        if (this.info.extension.getTableData && this.info.extension.getTableData.value.length > 0) {
          data = this.vuiComponents[this.info.extension.getTableData.value[0]].ref.getCheckboxRecords()
        } else {
          data = []
        }
        if (data.length > 0) {
          data.forEach((row) => {
            request.push({ ...row, ...obj, '#SQL_MODE#': this.value })
          })
        } else {
          if (this.info.extension.templateOptions) {
            console.log(this.info.extension.templateOptions.value)
            this.info.extension.templateOptions.value.forEach((r) => {
              let customizeObj = {}
              if (r.customize && r.customize.length > 0 && r.customize[0].value) {
                r.customize.forEach((r) => {
                  customizeObj[r.key] = r.value
                })
              }
              console.log(customizeObj)
              request.push({ ...obj, ...customizeObj, '#SQL_MODE#': this.value })
            })
          } else {
            request.push({ ...obj, '#SQL_MODE#': this.value })
          }
        }
        console.log(request)
        return JSON.stringify(request)
        // this.options.postData.data = JSON.stringify(request)
      },
      //点击上传
      clickUpload() {
        console.log(this.$refs[`fileUploadRef${this.info._id}`])
        if (this.$refs[`fileUploadRef${this.info._id}`].allImgNum) {
          this.$refs[`fileUploadRef${this.info._id}`].submitUpload()
        } else {
          this.$message({
            type: 'error',
            message: translateTitle('Ve.elements.请选择文件'),
          })
        }
      },
      confirmDialog() {
        this.close()
      },
      close() {
        let tableId = this.info.extension.getTable.value[0] //选择的表格ID
        if (tableId) {
          let _table = this.vuiComponents[tableId]
          if (_table) {
            _table.self.$refreshTable()
          } else {
            console.log('表格刷新没有找到表格')
          }
        }
        this.toleadModal = false
        this.active = 1
      },
      //上传成功
      uploadSuccess(file) {
        let res = file.fileList[0].response
        console.log(res)
        if (res.code === '00000') {
          this.active++
          this.$baseMessage(translateTitle('Ve.elements.上传成功'), 'success')
          this.toleadSuccess = true
          // this.threeNext()
        } else {
          this.$baseMessage(res.msg, 'error', undefined, true)
          this.active++
          this.toleadSuccess = false
          if (res.data) {
            this.gridOptions.data = res.data
          }
          this.$nextTick(() => {
            document.getElementsByClassName('err-msg')[0].innerHTML = res.msg
          })
        }
      },
      $openModel(val) {
        this.toleadModal = val
      },
      //打开导入弹框
      openTolead() {
        if (!this.hasPreview) {
          return
        }
        console.log(this.info.interaction)
        if (this.info.interaction.length == 0) {
          //未配置事件
          this.toleadModal = true
        } else {
          this.runEventTask('onClick')
        }
      },
      dialogClose() {
        this.close()
      },
      //模板下载
      async download() {
        console.log(this.info)
        let subList = []
        if (this.info.extension.subSystem && this.info.extension.subSystem.value) {
          subList.push({
            '#EXPORT_WHERE#': {
              TEMPLATE_ID: this.info.extension.tableName.value,
            },
            '#EXPORT_SQL_ID#': this.info.extension.templateMethod.value,
            '#EXPORT_API_NAME#': this.info.extension.templateMethod.value,
          })
        } else {
          let obj = {}
          if (this.info.extension.requestData && this.info.extension.requestData.value) {
            this.info.extension.requestData.value.forEach((row) => {
              obj[row.key] = row.value
            })
          }
          this.info.extension.templateOptions.value.forEach((row) => {
            let customizeObj = {}
            if (row.customize && row.customize.length > 0 && row.customize[0].value) {
              row.customize.forEach((r) => {
                customizeObj[r.key] = r.value
              })
            }
            subList.push({
              ...this.templateForm,
              ...obj,
              ...customizeObj,
              '#EXPORT_WHERE#': {
                TEMPLATE_ID: row.TABLE_NAME,
                FIELD_ID: row.FIELD_NAME,
              },
              '#EXPORT_SQL_ID#': this.info.extension.templateMethod.value,
              '#EXPORT_API_NAME#': this.info.extension.templateMethod.value,
              '#EXPORT_SHEET_NAME#': row.EXPORT_SHEET_NAME,
            })
          })
        }
        let res = await request({
          // url: 'http://192.168.3.211/wms/wms-web',
          url: GFCD('dams', 'domain') + this.info.extension.templateUrl.value,
          method: 'post',
          data: {
            data: JSON.stringify(subList),
            method: this.info.extension.templateMethod.value,
          },
          responseType: 'blob',
        })
        let blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        let reader = new FileReader()
        reader.readAsDataURL(blob) // 转换为base64，可以直接放入a标签href
        reader.onload = (e) => {
          let a = document.createElement('a')
          a.download = this.info.extension.templateName.value ? this.info.extension.templateName.value : translateTitle('Ve.elements.模板') + '.xlsx'
          a.href = e.target.result
          a.click()
        }
      },
    },
  })
</script>
<style lang="scss" scoped>
  // :deep() .el-step__title.is-finish {
  //   font-weight: 700;
  //   color: #000;
  // }
  // :deep().el-step__title.is-process {
  //   color: #c2c2c2;
  // }
  // :deep().el-step__head.is-finish {
  //   border-color: #3270ff;
  // }
  // :deep().el-step__head.is-process {
  //   border-color: #c2c2c2;
  // }
  // :deep().is-finish .el-step__icon.is-text {
  //   background-color: #3270ff;
  //   color: #fff;
  // }
  // :deep().is-process .el-step__icon.is-text {
  //   color: #c2c2c2;
  // }
  .footer_ {
    margin-top: 20px;
    text-align: center;
  }
  .flex_ {
    display: flex;
    justify-content: space-between;
  }
  .el-select .el-input .el-input__inner,
  .el-radio-group {
    width: 193px !important;
  }
  .hint_ {
    background: #fff5e6;
    padding: 15px 30px;
    box-sizing: border-box;
    .hint-title {
      font-weight: 600;
    }
    .hint-explain {
      margin-top: 10px;
      font-size: 14px;
      text-align: center;
      color: #666666;
    }
  }
  .step-two {
    margin-top: 20px;
  }
  .box_ {
    margin-top: 20px;
    display: flex;
    align-items: center;
    height: 115px;
    border: 1px solid #d8d3d3;
    p {
      margin-top: 10px;
    }
    .right-width {
      width: calc(100% - 50px);
    }
    .text-color {
      color: #3270ff;
      font-size: 16px;
    }
    .text-tips {
      font-size: 12px;
      color: #999999;
    }
  }
  .left-box {
    width: 50px;
    height: 100%;
  }
  .status {
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 50%;
  }
  .status-error {
    background-color: #f0463a;
  }
  .status-success {
    background-color: #10a54f;
  }
  .abnormal-hint {
    padding: 15px;
    margin-top: 20px;
    box-sizing: border-box;
    border: 1px solid #f5f5f5;
    p {
      margin-top: 10px;
    }
  }
  .success {
    display: flex;
    justify-content: center;
    align-items: center;
    & > div {
      height: 300px;
    }
  }
  .abnormal-hint {
    padding: 15px;
    margin-top: 20px;
    box-sizing: border-box;
    border: 1px solid #f5f5f5;
    p {
      margin-top: 10px;
    }
  }
</style>
